package me.firstapp.bbs.base;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.remoting.RemoteConnectFailureException;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.AbstractJsonObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.JsonMember;
import me.firstapp.common.module.shop.JsonShoppingCart;
import me.firstapp.common.module.shop.JsonShoppingCartItem;
import me.firstapp.common.module.shop.TempshoppingCart;
import me.firstapp.common.module.shop.TempshoppingCartItem;
import me.firstapp.common.utils.CookieUtils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.spi.bbs.MemberService;
import me.firstapp.spi.shop.ShoppingCartService;

@Service
public class BaseController implements HandlerExceptionResolver {
	private static final String SERVICE_EXCEPTION = "_exception";
	private static final String ERROR_PAGE = "error/error";

	@Autowired
	protected MemberService memberService;

	@Autowired
	protected ShoppingCartService shoppingCartService;

	@Autowired
	protected RedisTemplate<String, Object> redisTemplate;

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception e) {

		e.printStackTrace();
		ModelMap modelMap = new ModelMap();

		if (e instanceof ServiceException) {
			ServiceException serviceException = (ServiceException) e;
			if (request.getRequestURI().endsWith(".do")) {
				AbstractJsonObject abstractJsonObject = new AbstractJsonObject();
				abstractJsonObject.setCode(serviceException.getCode());
				abstractJsonObject.setMsg(serviceException.getStatusObject().getMsg());
				ResponseUtils.renderJson(response, abstractJsonObject);
				return new ModelAndView();
			}
			modelMap.put(SERVICE_EXCEPTION, serviceException);
			return new ModelAndView(ERROR_PAGE, modelMap);
		} else if (e instanceof RemoteConnectFailureException) {
			modelMap.put(SERVICE_EXCEPTION, new ServiceException(StatusHouse.COMMON_STATUS_REQUEST_TIMEOUT));
			return new ModelAndView(ERROR_PAGE, modelMap);
		} else {
			return new ModelAndView(ERROR_PAGE, modelMap);
		}

	}

	/**
	 * 获取登录用户的loginToken
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 */
	protected String getCurrentLoginToken(HttpServletRequest request, HttpServletResponse response) {
		String loginToken = getCookieLoginToken(request);
		return loginToken;
	}

	/**
	 * 获取登录用户的MemberId,如果没获取到，会抛异常
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 */
	protected JsonMember getCurrentLoginMember(HttpServletRequest request, HttpServletResponse response) {
		JsonMember member = getLoginMember(request, response);
		if (member == null) {
			throw new ServiceException(StatusHouse.COMMON_NO_LOGIN_OR_TIMEOUT);
		}
		return member;
	}

	protected Long getCurrentLoginMemberId(HttpServletRequest request, HttpServletResponse response) {
		return getCurrentLoginMember(request, response).getId();
	}

	protected Long getLoginMemberId(HttpServletRequest request, HttpServletResponse response) {
		JsonMember member = getLoginMember(request, response);
		if (member == null) {
			return null;
		}
		return member.getId();
	}

	/**
	 * 获取登录用户的MemberId
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	protected JsonMember getLoginMember(HttpServletRequest request, HttpServletResponse response) {
		String loginToken = getCurrentLoginToken(request, response);
		if (StrUtils.isNotNULL(loginToken)) {
			JsonMember member = (JsonMember) redisTemplate.opsForValue().get("login_member_" + loginToken);
			return member;
		} else {
			return null;
		}
	}

	/**
	 * 将登录token放入cookie中
	 * 
	 * @param response
	 * @param loginToken
	 */
	protected void setCookieLoginToken(HttpServletResponse response, String loginToken) {
		Cookie userCookie = new Cookie("loginToken", loginToken);
		userCookie.setMaxAge(7 * 24 * 60 * 60); // 存活期为7天
		userCookie.setPath("/");// 设置路径，这个路径即该工程下都可以访问该cookie
								// 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
		response.addCookie(userCookie);
	}

	protected String getCookieLoginToken(HttpServletRequest request) {
		Cookie cookie = CookieUtils.getCookieByName(request, "loginToken");
		if (cookie != null) {
			return cookie.getValue();
		} else {
			return null;
		}

	}


	/**
	 * 购物车获取
	 * 
	 * @param request
	 * @param response
	 */
	protected TempshoppingCart getTempshoppingCart(HttpServletRequest request, HttpServletResponse response) {
		TempshoppingCart tempShoppingCart = (TempshoppingCart) request.getSession().getAttribute("shoppingCart");
		if (tempShoppingCart == null) {
			tempShoppingCart = new TempshoppingCart();
		}
		JsonMember member = getLoginMember(request, response);
		if (member != null) {
			SingleObject<JsonShoppingCart> shoppingCartResult = shoppingCartService
					.findMemberShoppingCart(member.getId());
			JsonShoppingCart shoppingCart = shoppingCartResult.getObject();
			if (shoppingCart != null) {
				tempShoppingCart.setCounts(shoppingCart.getCounts());
				tempShoppingCart.setValue(shoppingCart.getValue());

				List<JsonShoppingCartItem> shoppingCartItemList = shoppingCart.getItems();
				List<TempshoppingCartItem> tempshoppingCartItems = new ArrayList<>();
				if (shoppingCartItemList != null) {
					for (JsonShoppingCartItem shoppingCartItem : shoppingCartItemList) {
						TempshoppingCartItem tempshoppingCartItem = new TempshoppingCartItem();
						tempshoppingCartItem.setCounts(shoppingCartItem.getCounts());
						tempshoppingCartItem.setProductId(shoppingCartItem.getProduct().getId());
						tempshoppingCartItem.setProductName(shoppingCartItem.getProduct().getName());
						tempshoppingCartItem.setSmallImage(shoppingCartItem.getProduct().getSmallImage());
						tempshoppingCartItem.setValue(shoppingCartItem.getValue());
						tempshoppingCartItem.setPrice(shoppingCartItem.getProductSkuRelation().getPrice());
						tempshoppingCartItem.setProductSkuRelId(shoppingCartItem.getProductSkuRelation().getId());
						tempshoppingCartItem.setSkuValue1(shoppingCartItem.getProductSkuRelation().getSkuValue1());
						tempshoppingCartItem.setSkuValue2(shoppingCartItem.getProductSkuRelation().getSkuValue2());
						tempshoppingCartItems.add(tempshoppingCartItem);
					}
				}
				tempShoppingCart.setItems(tempshoppingCartItems);
			}
		}
		return tempShoppingCart;
	}
}
